import axios from 'axios'
import { restUrl } from '../../url'
import router from '../router'

//定义fetch函数，config为配置
export function fetch(config){


  //返回promise对象
  return new Promise((resolve,reject) =>{
    //创建axios实例，把基本的配置放进去
    const instance = axios.create({
      //定义请求文件类型
      headers:{
        'Content-Type': config.content,
      },
      // 请求超时
      timeout: 90000,
      //定义请求根目录
      baseURL: config.request,
      data:config.data
    });

    instance.interceptors.request.use(function (config) {
      if (window.localStorage.getItem('water_token')){
        config.headers.common['token'] = window.localStorage.getItem('water_token');
      }
      return config
    },function (error) {
      return Promise.reject(error)
    });

    instance.interceptors.response.use(function (res) {
      // 排除用户端登录接口，以免token互串
      if (res.headers.token) {
        localStorage.setItem('water_token',res.headers.token);
      }
      if (res.data.status==600){
        router.push('/');
        localStorage.clear();
      }
      return res
    },function (error) {
      return Promise.reject(error)
    });

    //请求成功后执行的函数
    instance(config).then(res =>{
      resolve(res);
      //失败后执行的函数
    }).catch(err => {
      console.log(err);
      reject(err);
    })
  });
}

// 封装调用的接口 getData
export function getData(url,type,data,content,request) {
  //如果type为空，默认为post方法，也可以自己改成get
  if(type==='')
    type = 'post';
  if (!content) {
    content='application/json'
  }
  return fetch({
    url: url,
    method: type,
    data: data,
    content:content,
    request:request?request:restUrl
  })
}

export function getExel(url, params, index) {
  return new Promise(function(resolve, reject) {
    let data = {
      method: "GET",
      url:url,
      responseType: 'arraybuffer'
    }
    resolve(axios(data));
  })
}
